package cn.wowjoy.office.materialinspection.check.task;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseActivity;
import cn.wowjoy.office.common.customview.MaskFramLayout;
import cn.wowjoy.office.common.decoration.SimpleItemDecoration;
import cn.wowjoy.office.common.widget.CreateDialog;
import cn.wowjoy.office.common.widget.MDialog;
import cn.wowjoy.office.data.mock.PopuModel;
import cn.wowjoy.office.data.response.CheckBroadResultResponse;
import cn.wowjoy.office.data.response.InventoryTaskDtlVO;
import cn.wowjoy.office.data.response.InventoryTaskDetailListResponse;
import cn.wowjoy.office.databinding.ActivityCheckTaskListBinding;
import cn.wowjoy.office.materialinspection.check.detail.CheckDetailActivity;
import cn.wowjoy.office.materialinspection.check.detail.add.CheckAddActivity;
import cn.wowjoy.office.materialinspection.check.task.abnormal.AbNormalActivity;
import cn.wowjoy.office.materialinspection.check.task.count.CheckCountActivity;
import cn.wowjoy.office.materialinspection.check.task.search.CheckTaskListSearchActivity;
import cn.wowjoy.office.utils.MD5Util;

public class CheckTaskListActivity extends NewBaseActivity<ActivityCheckTaskListBinding, CheckTaskListViewModel> implements View.OnClickListener {


    @Override
    protected Class<CheckTaskListViewModel> getViewModel() {
        return CheckTaskListViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_task_list;
    }

    private static final int REQUEST_CODE = 0x00000011;
    boolean isSelected = false;
    private int initHeight;

    private MDialog mDialog; //back提示
    private MDialog submitDialog;//提交失败

    String taskId;   //唯一索引
    boolean isDone;  // 是否完成
    String billNo;
    private String key; //关键词


    @Override
    protected void init(Bundle savedInstanceState) {
        binding.setViewModel(viewModel);

        initView();
        initSearch();
        initMenu();
        initFilter();//初始化Filter
        initObserve();
    }

    private void initSearch() {
        binding.searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                hideSoftInput();
                key = binding.searchEditText.getText().toString().trim();
                switchFilter2(key, true);
                return true;
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO：联网模糊查询
                if (!TextUtils.isEmpty(binding.searchEditText.getText().toString())) {
                    binding.delete.setVisibility(View.VISIBLE);
                } else {
                    binding.delete.setVisibility(View.GONE);
                    key = null;
                }
            }
        });
        binding.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchEditText.setText("");
            }
        });
    }

    private void initView() {
        binding.patrolTaskTitle.titleTextTv.setText("盘点任务");
        binding.patrolTaskTitle.titleBackLl.setVisibility(View.VISIBLE);
        binding.patrolTaskTitle.titleBackTv.setText("");
        binding.patrolTaskTitle.titleBackLl.setOnClickListener(this);

        binding.patrolTaskTitle.titleMenuConfirm.setVisibility(View.VISIBLE);
        binding.patrolTaskTitle.titleMenuConfirm.setTextColor(getResources().getColor(R.color.white));
        binding.patrolTaskTitle.titleMenuConfirm.setOnClickListener(this);
        taskId = getIntent().getExtras().getString("taskId");
        isDone = getIntent().getExtras().getBoolean("isDone");
        billNo = getIntent().getExtras().getString("billNo");
        if (null != billNo && !"".equals(billNo)) {
            binding.detailCheck.setText(billNo);
        }
        if (isDone) {
            binding.llNodoneFunction.setVisibility(View.GONE);
            binding.divider.setVisibility(View.VISIBLE);

            binding.searchBar.setVisibility(View.VISIBLE);
            binding.divider.setVisibility(View.VISIBLE);
        } else {
            binding.llNodoneFunction.setVisibility(View.VISIBLE);
            binding.divider.setVisibility(View.GONE);
         //0101012017  004
            binding.searchBar.setVisibility(View.GONE);
            binding.divider.setVisibility(View.GONE);
        }

        binding.rlAddCheck.setOnClickListener(this);
        binding.rlAddSearch.setOnClickListener(this);

        binding.rvCheck.setLayoutManager(new LinearLayoutManager(this));
        binding.rvCheck.setAdapter(viewModel.wladapter);
        binding.rvCheck.setEmptyView(binding.emptyView.getRoot());
        binding.rvCheck.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                //下拉刷新 请求服务器新数据
                if (null != taskId && !"".equals(taskId)) {
                    setFilterText(filter);
                }
            }
        });
    }

    private List<PopuModel> popuModels;

    public void createMeun() {
        if (null == popuModels)
            popuModels = new ArrayList<>();
        if (popuModels.isEmpty()) {
            popuModels.add(new PopuModel("全部", true, ""));
            if (!isDone) {
                popuModels.add(new PopuModel("未盘点", false, ""));
            }
            popuModels.add(new PopuModel("正常", false, ""));
            popuModels.add(new PopuModel("盘盈", false, ""));
            popuModels.add(new PopuModel("盘亏", false, ""));
        }
        viewModel.menuAdapter.setPopuModels(popuModels);
    }

    private void initMenu() {
        binding.meunRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        binding.meunRecyclerview.setAdapter(viewModel.menuAdapter);
        binding.meunRecyclerview.addItemDecoration(new SimpleItemDecoration(this, SimpleItemDecoration.VERTICAL_LIST));
        createMeun();
    }

    private MDialog waitDialog;

    private void initObserve() {
        viewModel.getResponse().observe(this, new Observer<LiveDataWrapper<InventoryTaskDetailListResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<InventoryTaskDetailListResponse> InventoryTaskDetailListResponseLiveDataWrapper) {
                if (InventoryTaskDetailListResponseLiveDataWrapper != null) {
                    switch (InventoryTaskDetailListResponseLiveDataWrapper.status) {
                        case LOADING:
                            waitDialog = CreateDialog.waitingDialog(CheckTaskListActivity.this);
                            break;
                        case SUCCESS:
                            if (null != waitDialog) {
                                CreateDialog.dismiss(CheckTaskListActivity.this, waitDialog);
                            }
                            updateUI(InventoryTaskDetailListResponseLiveDataWrapper.data, filter);
                            break;
                        case ERROR:
                            if (null != waitDialog) {
                                CreateDialog.dismiss(CheckTaskListActivity.this, waitDialog);
                            }
                            handleException(InventoryTaskDetailListResponseLiveDataWrapper.error, true);
                            break;
                    }
                }
            }
        });

        viewModel.getLoad().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                setFilterText(filter.trim(), aBoolean.booleanValue());
            }
        });

        viewModel.getJump().observe(this, new Observer<InventoryTaskDtlVO>() {
            @Override
            public void onChanged(@Nullable InventoryTaskDtlVO InventoryTaskDtlVO) {
                jump(InventoryTaskDtlVO);
            }
        });

        viewModel.meun.observe(this, new Observer<PopuModel>() {
            @Override
            public void onChanged(@Nullable PopuModel popuModel) {
                sort(popuModel);
            }
        });
        viewModel.getBroadResult().observe(this, new Observer<LiveDataWrapper<CheckBroadResultResponse>>() {
            @Override
            public void onChanged(@Nullable LiveDataWrapper<CheckBroadResultResponse> submitCheckTaskListDetailResponseLiveDataWrapper) {
                switch (submitCheckTaskListDetailResponseLiveDataWrapper.status) {
                    case LOADING:
                        waitDialog = CreateDialog.waitingDialog(CheckTaskListActivity.this);
                        break;
                    case SUCCESS:
                        waitDialog.dismiss();
                        //强提示  弹框表示
                        if (null != submitCheckTaskListDetailResponseLiveDataWrapper.data && "该设备不在本次盘点范围内".equals(submitCheckTaskListDetailResponseLiveDataWrapper.data.getInfo()) && !"N".equalsIgnoreCase(submitCheckTaskListDetailResponseLiveDataWrapper.data.getInSystem())) {
                            Intent intent = new Intent(CheckTaskListActivity.this, AbNormalActivity.class);
                            intent.putExtra("error", 1);
                            intent.putExtra("data", submitCheckTaskListDetailResponseLiveDataWrapper.data);
                            startActivity(intent);
                        } else if (null != submitCheckTaskListDetailResponseLiveDataWrapper.data && "N".equalsIgnoreCase(submitCheckTaskListDetailResponseLiveDataWrapper.data.getInSystem())) {
                            Intent intent = new Intent(CheckTaskListActivity.this, AbNormalActivity.class);
                            intent.putExtra("error", 0);
                            startActivity(intent);
                        } else {
                            mDialog = CreateDialog.submitDialog(CheckTaskListActivity.this, "盘点成功", submitCheckTaskListDetailResponseLiveDataWrapper.data.getInfo(), 102, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (null != mDialog) {
                                        mDialog.cancel();
                                    }
                                    binding.rvCheck.refresh();
                                }
                            }, "好的");
                        }
                        break;
                    case ERROR:
                        waitDialog.dismiss();
                        Throwable throwable = submitCheckTaskListDetailResponseLiveDataWrapper.error;
                        handleException(throwable, false);
                }
            }
        });
    }


    private void initFilter() {
        binding.tvFilterPatrolTask.setSelected(false);
        binding.tvFilterPatrolTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeErrorview();
                if (isSelected) {
                    closeFolder();

                } else {
                    openFolder();
                }
                binding.tvFilterPatrolTask.setSelected(isSelected);

            }
        });
        //展示巡检设备清单的状态筛选 下拉
        binding.maskLr.setDimissListener(new MaskFramLayout.DimissListener() {
            @Override
            public void onDismiss() {
                isSelected = false;
                binding.tvFilterPatrolTask.setSelected(false);
                binding.maskLr.setVisibility(View.GONE);

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isDone) {
            openBroadCast();
        }
        binding.rvCheck.refresh();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (!isDone) {
            closeBroadCast();
        }
    }

    @Override
    public void onBackPressed() {
        if (!isDone) {
            mDialog = CreateDialog.infoDialog(CheckTaskListActivity.this, "提醒", "该盘点任务还未提交，是否退出", "否", "是", v12 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                }
            }, v1 -> {
                if (null != mDialog) {
                    mDialog.cancel();
                    finish();
                }
            });
        } else {
            finish();
        }
    }

    /**
     * 弹出文件夹列表
     */
    protected void openFolder() {

        hideSoftInput();
        if (!isSelected) {
            binding.maskLr.setVisibility(View.VISIBLE);
            if (binding.meunRecyclerview.getHeight() != 0) {
                initHeight = binding.meunRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.meunRecyclerview, "translationY",
                    -initHeight, 0).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    binding.meunRecyclerview.setVisibility(View.VISIBLE);
                }
            });
            animator.start();
            isSelected = true;
        }
    }

    protected void setFloder(PopuModel popuModel) {
        binding.tvFilterPatrolTask.setText(popuModel.getName());
//        isStop = popuModel.getStatus();
    }


    /**
     * 收起文件夹列表
     */
    protected void closeFolder() {

        hideSoftInput();
        if (isSelected) {
            if (binding.meunRecyclerview.getHeight() != 0) {
                initHeight = binding.meunRecyclerview.getHeight();
            }
            ObjectAnimator animator = ObjectAnimator.ofFloat(binding.meunRecyclerview, "translationY",
                    0, -initHeight).setDuration(300);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    binding.meunRecyclerview.setVisibility(View.GONE);
                    binding.maskLr.setVisibility(View.GONE);
                }
            });
            animator.start();
            isSelected = false;
        }
    }

    public void sort(PopuModel popuModel) {
        setFloder(popuModel);
        closeFolder();
//        Toast.makeText(this,popuModel.getName(),Toast.LENGTH_SHORT).show();
        setFilterText(popuModel.getName(), true);
    }

    public void updateUI(InventoryTaskDetailListResponse taskListResponse, String status) {
        if (isDone) {
            binding.patrolTaskTitle.titleMenuConfirm.setText("统计");
        } else {
            binding.patrolTaskTitle.titleMenuConfirm.setText("提交");
        }
        if (null != taskListResponse) {
            if ("0".equals(taskListResponse.getTotalCount())) {
                binding.tvFilterPatrolTask.setText(status);
            } else {
                binding.tvFilterPatrolTask.setText(status + "(" + taskListResponse.getTotalCount() + ")");
            }
        }

    }

    // 筛选菜单的文字
    public void setFilterText(String state) {
        isSelected = false;
        binding.tvFilterPatrolTask.setSelected(false);
        binding.maskLr.setVisibility(View.GONE);
//        binding.rlAnim.setVisibility(View.VISIBLE);
        binding.tvFilterPatrolTask.setText(state);
        switchRequest(state, true);
    }

    // 筛选菜单的文字
    public void setFilterText(String state, boolean ref) {
        isSelected = false;
        binding.tvFilterPatrolTask.setSelected(false);
        binding.maskLr.setVisibility(View.GONE);
        binding.tvFilterPatrolTask.setText(state);
        switchRequest(state, ref);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back_ll:
                //弹框提示
                if (!isDone) {
                    mDialog = CreateDialog.infoDialog(CheckTaskListActivity.this, "提醒", "该盘点任务还未提交，是否退出", "否", "是", v12 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                        }
                    }, v1 -> {
                        if (null != mDialog) {
                            mDialog.cancel();
                            finish();
                        }
                    });
                } else {
                    finish();
                }
                break;
            case R.id.title_menu_confirm:
                //未完成Task 提交任务   ----检查是否全部做过，并且提示
                if (null == taskId || "".equals(taskId)) {
                    finish();
                    return;
                }
                if ("提交".equals(binding.patrolTaskTitle.titleMenuConfirm.getText().toString())) {
                    viewModel.submitPDA(taskId)
                            .observe(this, new Observer<LiveDataWrapper<Boolean>>() {
                                @Override
                                public void onChanged(@Nullable LiveDataWrapper<Boolean> booleanLiveDataWrapper) {
                                    switch (booleanLiveDataWrapper.status) {
                                        case LOADING:
                                            waitDialog = CreateDialog.waitingDialog(CheckTaskListActivity.this);
                                            break;
                                        case SUCCESS:
                                            waitDialog.dismiss();
                                            finish();
                                            break;
                                        case ERROR:
                                            waitDialog.dismiss();
                                            Throwable throwable = booleanLiveDataWrapper.error;
                                            CreateDialog.submitDialog(CheckTaskListActivity.this, "提交失败", throwable.getMessage(), 101, null, "确定");
//                                                handleException(throwable, false);
                                            break;
                                    }
                                }
                            });
                } else if ("统计".equals(binding.patrolTaskTitle.titleMenuConfirm.getText().toString())) {
                    //统计
                    Intent intent2 = new Intent(CheckTaskListActivity.this, CheckCountActivity.class);
                    intent2.putExtra("taskId", taskId);
                    startActivity(intent2);
                }
                break;
            case R.id.rl_add_check:
                // 新增盘盈
                Intent intent = new Intent(this, CheckAddActivity.class);
                intent.putExtra("taskId", taskId);
                startActivity(intent);
                break;

            case R.id.rl_add_search:
                //搜索
                Intent intent1 = new Intent(this, CheckTaskListSearchActivity.class);
                intent1.putExtra("isDone", isDone);
                intent1.putExtra("taskId", taskId);
                startActivity(intent1);
                break;
        }
    }

    // 未盘点 0    盘盈1   已盘 2  差异3  盘亏4  正常5   全部什么都不传
    public void switchFilter2(String billInfo, boolean refresh) {
        switch (filter) {
            case "全部":
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "", billInfo, refresh, filter);
                break;
            case "未盘点":
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "0", billInfo, refresh, filter);
                break;
            case "盘盈":
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "1", billInfo, refresh, filter);
                break;
            case "盘亏":
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "4", billInfo, refresh, filter);
                break;
            case "正常":
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "5", billInfo, refresh, filter);
                break;
            default:
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "", "", refresh, filter);
                break;
        }
    }

    // 未盘点 0    盘盈1   已盘 2  差异3  盘亏4  正常5   全部什么都不传
    public void switchFilter(String string, boolean refresh) {
        switch (string) {
            case "全部":
                filter = "全部";
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "", "", refresh, filter);
                break;
            case "未盘点":
                filter = "未盘点";
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "0", "", refresh, filter);
                break;
            case "盘盈":
                filter = "盘盈";
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "1", "", refresh, filter);
                break;
            case "正常":
                filter = "正常";
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "5", "", refresh, filter);
                break;
            case "盘亏":
                filter = "盘亏";
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "4", "", refresh, filter);
                break;

            default:
                viewModel.getInventoryTaskListControllerByPageSize(taskId, "", "", refresh, filter);
                break;
        }
    }

    public String filter = "全部";

    public void switchRequest(String text, boolean refresh) {
        if (null == text || "".equals(text)) {
            viewModel.getInventoryTaskListControllerByPageSize(taskId, "", "", refresh, filter);
            return;
        }
        switchFilter(text, refresh);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mDialog) {
            mDialog.cancel();
        }
        if (null != submitDialog) {
            submitDialog.cancel();
        }
    }

    public boolean isUUID(String qrCode) {
        if (null != qrCode && !"".equals(qrCode)) {
            if (!MD5Util.IsUUID(qrCode)) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected void brodcast(Context context, String msg) {
        super.brodcast(context, msg);
        String qrCode = msg;
//        Log.e("PXY", "brodcast: "+qrCode.toString());
        //扫到的二维码信息 填入到搜索栏中
        if (!isUUID(qrCode)) {
            //不符合UUID  误操作扫描非盘点二维码  跳转页面 显示扫描错误
            Intent intent = new Intent(CheckTaskListActivity.this, AbNormalActivity.class);
            intent.putExtra("error", 0);
            startActivity(intent);
        } else {
            // 请求服务器去更新状态   1.成功 2.失败 失败进行跳转显示不在巡检范围
            if (null != taskId && !"".equals(taskId)) {
                viewModel.updateByBroad(qrCode, taskId);
            }

        }
    }

    @Override
    protected void refreshError() {
        super.refreshError();
        setFilterText(binding.tvFilterPatrolTask.getText().toString().trim());
    }

    @Override
    protected ViewGroup getErrorViewRoot() {
        return binding.flEmpty;
    }


    public void jump(InventoryTaskDtlVO inspectTaskDtlVO) {
        Intent intent = new Intent(this, CheckDetailActivity.class);
        intent.putExtra("taskId", taskId);
        intent.putExtra("taskDtlId", inspectTaskDtlVO.getId());
        intent.putExtra("data", inspectTaskDtlVO);
        intent.putExtra("isDone", isDone);
        startActivity(intent);
    }
}
